<template>
  <div v-if="visible" v-loading="loading">
    <vxe-grid
      ref="grid"
      resizable
      show-overflow
      highlight-hover-row
      keep-source
      row-id="id"
      height="300"
      :data="tableData"
      :columns="tableColumn"
      :toolbar-config="toolbarConfig"
    >
      <!-- 工具栏 -->
      <template #toolbar_buttons>
        <a-space v-if="!readOnly">
          <a-button type="primary" @click="openBatchAddProductDialog">新增</a-button>
          <a-button danger @click="delProduct">删除</a-button>
        </a-space>
      </template>
      <!-- 商品名称 列自定义内容 -->
      <template #productName_default="{ row }">
        <span>{{ row.name }}</span>
      </template>

      <template #unit_default="{ row }">
        <unit-selector v-model:value="row.unit" readOnly />
      </template>

      <template
        v-for="(item, index) in extendColumn.filter((col) => col?.slots?.default)"
        :key="index"
        #[item?.slots?.default]="data"
      >
        <slot :name="item?.slots?.default" v-bind="data" :readOnly="readOnly"></slot>
      </template>
    </vxe-grid>
    <batch-add-product ref="batchAddProductDialog" :sc-id="'1234'" @confirm="addProduct" />
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, getCurrentInstance, PropType, watch } from 'vue';
  import { VxeTableDefines } from 'vxe-pc-ui';
  import * as productApi from '@/api/base-data/product/info';
  import BatchAddProduct from '@/views/sc/sale/batch-add-product.vue';
  import UnitSelector from '@/components/Selector/src/UnitSelector.vue';

  // this对象
  const instance: any = getCurrentInstance();

  // 商品ID列表
  const productId = defineModel('productId', {
    type: Array as PropType<string[]>,
    default: () => [],
  });

  const productValue = defineModel('productValue', {
    type: Object as PropType<any>,
    default: () => {},
  });

  // 表格数据
  const tableData = ref<Array<any>>([]);

  const props = defineProps({
    extendColumn: {
      type: Array as PropType<VxeTableDefines.ColumnOptions[]>,
      default: () => [],
    },
    visible: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
  });

  const grid = ref();

  const batchAddProductDialog = ref();

  const loading = ref(false);

  // 表格列配置
  const tableColumn = reactive<VxeTableDefines.ColumnOptions[]>([
    { type: 'checkbox', width: 45, visible: !props.readOnly },
    { field: 'code', title: '商品编号', width: 120 },
    {
      field: 'name',
      title: '商品名称',
      width: 140,
      slots: { default: 'productName_default' },
    },
    { field: 'unit', title: '单位', width: 80, slots: { default: 'unit_default' } },
    { field: 'categoryName', title: '商品分类', width: 120 },
    ...props.extendColumn,
  ]);

  // 工具栏配置
  const toolbarConfig = reactive({
    // 缩放
    zoom: false,
    // 自定义表头
    custom: false,
    // 右侧是否显示刷新按钮
    refresh: false,
    // 自定义左侧工具栏
    slots: {
      buttons: 'toolbar_buttons',
    },
  });

  const openBatchAddProductDialog = () => {
    batchAddProductDialog.value.openDialog();
  };

  // 批量新增商品
  const addProduct = (productList: any[]) => {
    productList.forEach((item) => {
      tableData.value.push(emptyProduct());
      handleSelectProduct(tableData.value.length - 1, item);
    });
  };

  const emptyProduct = () => {
    return {
      id: _This().$utils.uuid(),
    };
  };

  // 选择商品
  const handleSelectProduct = (index, value) => {
    tableData.value[index] = {
      id: value.productId,
      code: value.productCode,
      name: value.productName,
      skuCode: value.skuCode,
      categoryName: value.categoryName,
      brandName: value.brandName,
      unit: value.unit,
    };
    productId.value.push(value.productId);
    productValue.value[value.productId] = {
      price: null,
    };
  };

  const delProduct = () => {
    const records = grid.value.getCheckboxRecords();
    if (_This().$utils.isEmpty(records)) {
      _This().$msg.createError('请选择要删除的商品数据！');
      return;
    }
    _This()
      .$msg.createConfirm('是否确定删除选中的商品？')
      .then(() => {
        const data = tableData.value.filter((t) => {
          const tmp = records.filter((item) => item.id === t?.id);
          return _This().$utils.isEmpty(tmp);
        });

        tableData.value = data;
      });
  };

  // 加载商品信息
  const loadProductInfo = () => {
    if (!_This().$utils.isEmpty(productId.value)) {
      loading.value = true;
      productApi
        .loadProduct(productId.value)
        .then((res) => {
          if (!_This().$utils.isEmpty(res)) {
            tableData.value = res;
          }
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      tableData.value = [];
    }
  };

  // 组件实例对象
  const _This = () => {
    return instance.appContext.config.globalProperties;
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        loadProductInfo();
      }
    },
    { immediate: true },
  );
</script>

<style scoped></style>
